package com.liuda066.forumssm.controller;

import com.liuda066.forumssm.common.AppResult;
import com.liuda066.forumssm.common.ResultCode;
import com.liuda066.forumssm.config.AppConfig;
import com.liuda066.forumssm.model.Message;
import com.liuda066.forumssm.model.User;
import com.liuda066.forumssm.services.IMessageService;
import com.liuda066.forumssm.services.IUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.Objects;

/**
 * @author : niu niu
 * @version : 1.0.0
 * @date : 2023/9/5 23:05
 */
@Api(tags = "站内信接口")
@RestController
@Slf4j
@RequestMapping("/message")
public class MessageController {
    @Resource
    private IMessageService iMessageService;

    @Resource
    private IUserService iUserService;

    @ApiOperation("发送站内信")
    @PostMapping("/send")
    public AppResult send(HttpServletRequest request,
                          @ApiParam(value = "接受用户Id") @RequestParam(value = "receiveUserId") @NonNull Long receiveUserId,
                          @ApiParam(value = "站内信内容") @RequestParam(value = "content") @NonNull String content) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + " , userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        if (Objects.equals(user.getId(), receiveUserId)) {
            log.warn(" 不能给自己发站内信, postUserId = " + user.getId() + ",receiveUserId = " + receiveUserId);
            return AppResult.failed(ResultCode.FAILED_CREATE);
        }
        User receiveUser = iUserService.selectById(receiveUserId);
        if (receiveUser == null || receiveUser.getDeleteState() != 0) {
            log.warn(ResultCode.FAILED_USER_NOT_EXISTS.toString() + ",receiveUserId = " + receiveUserId);
            return AppResult.failed(ResultCode.FAILED_USER_NOT_EXISTS);
        }
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(receiveUserId);
        message.setContent(content);
        iMessageService.create(message);
        return AppResult.success();
    }

    @ApiOperation("获取未读消息个数")
    @GetMapping("/getUnreadCount")
    public AppResult<Integer> getUnreadCount(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        Integer integer = iMessageService.selectUnreadCount(user.getId());
        return AppResult.success(integer);
    }

    @ApiOperation("查询用户的所有站内信")
    @GetMapping("/getAll")
    public AppResult<List<Message>> getAll(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        List<Message> result = iMessageService.selectByReceiveUserId(user.getId());
        return AppResult.success(result);
    }



    @ApiOperation("回复站内信")
    @PostMapping("/reply")
    public AppResult reply(HttpServletRequest request,
                           @ApiParam("要回复的站内信Id") @RequestParam(value = "repliedId") @NonNull Long repliedId,
                           @ApiParam("站内信的内容") @RequestParam(value = "content") @NonNull String content) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        if (user.getState() != 0) {
            log.warn(ResultCode.FAILED_USER_BANNED.toString() + " , userId = " + user.getId());
            return AppResult.failed(ResultCode.FAILED_USER_BANNED);
        }
        Message existsMessage = iMessageService.selectById(repliedId);

        if (existsMessage ==null || existsMessage.getDeleteState() == 1){
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        if (Objects.equals(user.getId(), existsMessage.getPostUserId())){
            return AppResult.failed("不能回复自己的站内信");
        }
        Message message = new Message();
        message.setPostUserId(user.getId());
        message.setReceiveUserId(existsMessage.getPostUserId());
        message.setContent(content);

        iMessageService.reply(repliedId,message);
        return AppResult.success();
    }
    @ApiOperation("读取站内信")
    @GetMapping("/markRead")
    public AppResult<Message> markRead(HttpServletRequest request,
                                   @ApiParam(value = "站内信Id") @RequestParam(value = "id") @NonNull Long id) {
        // 根据Id查询内容
        Message message = iMessageService.selectById(id);
        // 获取用户信息
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute(AppConfig.USER_SESSION_KEY);
        // 接收方不是自己
        if (message != null && user.getId() != message.getReceiveUserId()) {
            // 打印日志
            log.warn("查询了不属于自己的站内信：userId = " + user.getId() + ", receiveUserId = " + message.getReceiveUserId());
            // 返回错误结果
            return AppResult.failed(ResultCode.FAILED);
        }
        // 更新为已读状态
        Message update = new Message();
        update.setId(message.getId());
        update.setState((byte) 1); // 1 为已读状态
        iMessageService.updateStateById(message.getId(), (byte) 1);
        // 返回结果
        return AppResult.success(message);
    }
}
